package com.ehsunbehravesh.mypasswords.gui;

import com.ehsunbehravesh.mypasswords.Utils;
import com.ehsunbehravesh.mypasswords.entity.PasswordEntry;
import com.ehsunbehravesh.mypasswords.entity.PasswordTag;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

public class BrowseDialog extends javax.swing.JDialog {

  private JFrame parent;
  private PasswordTag[] tags;
  private String tagsCaption = "Tags";

  public BrowseDialog(JFrame parent, boolean modal) {
    super(parent, modal);
    this.parent = parent;
    initComponents();
    myInitComponents();
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    scpMain = new javax.swing.JScrollPane();
    treTags = new javax.swing.JTree();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Browse");

    treTags.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        treTagsKeyPressed(evt);
      }
    });
    scpMain.setViewportView(treTags);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(scpMain, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(scpMain, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void treTagsKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_treTagsKeyPressed
    treTagsKeyPress(evt);
  }//GEN-LAST:event_treTagsKeyPressed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JScrollPane scpMain;
  private javax.swing.JTree treTags;
  // End of variables declaration//GEN-END:variables

  private void myInitComponents() {
    Utils.setCenterOfParent(parent, this);
    setFont(parent.getFont());
    setComponentOrientation(parent.getComponentOrientation());

    treTags.addMouseListener(new MouseAdapter()     {

      public void mouseClicked(MouseEvent me) {
        doMouseClicked(me);
      }
    });
    
    MainFrame mainFrame = (MainFrame) getParent();
    if (mainFrame.getCurrentLanguage() != null) {
      changeLanguage(mainFrame.getCurrentLanguage());
    }    
    
    loadTags();
    displayTags();
  }

  private void doMouseClicked(MouseEvent me) {
    TreePath tp = treTags.getPathForLocation(me.getX(), me.getY());
    if (tp != null) {
      DefaultMutableTreeNode lastNode = (DefaultMutableTreeNode) tp.getLastPathComponent();
      if (lastNode.isLeaf() && lastNode.getAllowsChildren() == false) {
        PasswordEntry passwordEntry = (PasswordEntry) lastNode.getUserObject();
        PasswordEntry decryptedPasswordEntry = new PasswordEntry(passwordEntry.getId());
        if (decryptedPasswordEntry.load()) {
          if (me.getClickCount() == 2) {
            //JOptionPane.showMessageDialog(parent, String.format("<html>Password of <b>%s</b>: <small>%s</small></html>", decryptedPasswordEntry.getTitle(), decryptedPasswordEntry.getPassword()), "Password", JOptionPane.INFORMATION_MESSAGE);          
            MainFrame owner = (MainFrame) getOwner();
            owner.setPasswordEntry(decryptedPasswordEntry);
            owner.displayPasswordEntry();
            setVisible(false);
          }
        }
      }
    }
  }

  private void loadTags() {
    tags = PasswordTag.getAllTags();    
  }

  private void displayTags() {
    DefaultTreeModel model = (DefaultTreeModel) treTags.getModel();
    MutableTreeNode root = new DefaultMutableTreeNode(String.format(tagsCaption + " (%d)", tags.length), true);

    int i = 0;
    for (i = 0; i < tags.length; i++) {
      PasswordTag passwordTag = tags[i];
      PasswordEntry[] passwordEntries = passwordTag.readEntries();
      MutableTreeNode tagNode = new DefaultMutableTreeNode(passwordTag, true);
      root.insert(tagNode, i);
      for (int j = 0; j < passwordEntries.length; j++) {
        PasswordEntry passwordEntry = passwordEntries[j];
        MutableTreeNode passwordNode = new DefaultMutableTreeNode(passwordEntry, false);
        tagNode.insert(passwordNode, j);
      }
    }
    
    PasswordEntry[] passwordsWithoutTag = PasswordEntry.getPasswordEntriesWithoutTag();
    if (passwordsWithoutTag.length > 0) {
      MutableTreeNode tagNode = new DefaultMutableTreeNode(String.format("[no tag] (%d)", passwordsWithoutTag.length), true);
      for (int k = 0; k < passwordsWithoutTag.length; k++) {
        PasswordEntry passwordEntry = passwordsWithoutTag[k];
        MutableTreeNode passwordNode = new DefaultMutableTreeNode(passwordEntry, false);
        tagNode.insert(passwordNode, k);
      }
      root.insert(tagNode, i);
    }

    model.setRoot(root);
  }

  private void treTagsKeyPress(KeyEvent evt) {
    int key = evt.getKeyCode();
    if (key == 27) {
      setVisible(false);
      dispose();
    }
  }
  
  private void changeLanguage(Properties currentLanguage) {
    try {
      setDirection(currentLanguage.getProperty("direction"));
      setTitle(currentLanguage.getProperty("Browse"));
      tagsCaption = currentLanguage.getProperty("Tags");
      
      refresh();
    } catch (Exception ex) {
      JOptionPane.showMessageDialog(this, "Error occured in changing language!", "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
  
  private void setDirection(String direction) {
    if (direction.equals("rtl")) {
      setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      scpMain.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      
      for (int i = 0; i < scpMain.getComponents().length; i++) {
        Component component = scpMain.getComponents()[i];
        component.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      }
    } else if (direction.equals("ltr")) {
      setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      scpMain.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      
      for (int i = 0; i < scpMain.getComponents().length; i++) {
        Component component = scpMain.getComponents()[i];
        component.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
      }
    }
  }

  private void refresh() {
    scpMain.setVisible(false);
    scpMain.setVisible(true);
  }
}
